<?php
/**
 * oci_pdo 类
 * @author	jonah.fu
 * @date	2012-04-21
 */
class framework_base_pdomysql {

    /**
     * 返回的连接状态
     * @author	jonah.fu
     * @date	2012-04-21
     */
	public $debug=false;
    public $connected = FALSE;

    /**
     * 返回的pdo对象
     * @author	jonah.fu
     * @date	2012-04-21
     */
    public $dbh;
    protected $DbUserName, $DbPassWord, $DbConnectStr, $DbCharset;

    public static $_instance = array();

    private function __construct($type = 0, $autoClose = 0, $ociDbServer = array(), $ociConnectStr = "") {
        if (empty($ociDbServer))
            $DbServer = MYSQL_HOST;

        $dbName = MYSQL_DBNAME;
        $this -> DbUserName = MYSQL_USERNAME;
        $this -> DbPassWord = MYSQL_PASSWORD;
        try {
            $this -> dbh = new PDO("mysql:host=$DbServer;dbname=$dbName", $this -> DbUserName, $this -> DbPassWord, array(
                PDO::ATTR_PERSISTENT => $type,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . MYSQL_CHARSET,
                PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
                PDO::ATTR_AUTOCOMMIT => TRUE
            ));
            $this -> connected = TRUE;
			$this->execute('set names utf8');
        } catch ( Exception $e ) {
            printf($e -> getMessage());
            exit();
        }

        if ($autoClose) {
            register_shutdown_function(array(
                &$this,
                'close_pdooci'
            ));
        }
    }

    /**
     * 防止复制对象,因为单例模式要保证一个类实例的对象是唯一的.
     */
    private function __clone() {
    }

    /**
     * 返回的连接状态
     * @author	jonah.fu
     * @date	2012-04-21
     * @param	int			type			是否长联接
     * @param	int			autoClose		是否自动关闭连接
     * @param	int			autoClose		是否自动关闭
     * @param	array		ociDbServer		数据库信息，参考 config.php 文件
     * @param	string		ociConnectStr	数据库连接字符串，参考 config.php 文件
     *
     * @return	object		返回pdo_oci_obj 对象
     */
    public static function connect($type = 0, $autoClose = 0, $ociDbServer = array(), $ociConnectStr = "") {
        $arrStr = md5(json_encode((array)($ociDbServer)));
        if (empty(self::$_instance) || !(self::$_instance[$arrStr] instanceof self)) {

            // 如果是长联接则不自动关闭
            if ($type)
                $autoClose = 0;
            self::$_instance[$arrStr] = new self($type, $autoClose, $ociDbServer, $ociConnectStr);
        }
        return self::$_instance[$arrStr];
    }

    /**
     * 关闭连接
     * @author	jonah.fu
     * @date	2012-04-21
     */
    public function close_pdooci() {
        $this -> dbh = null;
    }

        
    //插入数据    
    public function insert($table,$data,$more='')
    {    
		$sql = "INSERT INTO `$table` SET ";    
		$binds=array();
		foreach($data as $k=>$v)
		{
			$sql .= '`'.$k.'`=:'.$k.',';//'.mysql_escape_string($v).'",';    
			$binds[':'.$k]=$v;
		}

        if(!empty($more)) {
            $sql .= $more;
        } else {
            $sql .= 'raw_add_time=NOW()';
        }

		try{
			$stmt=$this->dbh->prepare($sql);
			if($stmt->execute($binds))
				return $this->dbh->lastInsertId();	
		}catch(PDOException $e){
			$this->getPDOError();
		}
    } 
        
    //获取记录总数    
    public function counts($table,$where = '',$binds=array())    
    {    
        $sql = "SELECT COUNT(*) AS num FROM $table";    
		if($where)
			$sql .= ' where '.$where;    
		try{
			$stmt = $this->dbh->prepare($sql);    
			$stmt->execute($binds);
			return $stmt->fetchColumn();    
		}catch(PDOException $e){
			$this->getPDOError();    
		}
    }    
        
    //获取一行
    public function queryRow($sql,$binds=array())    
    {    
		//try{
			$stmt = $this->dbh->prepare($sql);    
			$stmt->execute($binds);
			$result = $stmt->fetch();    
			return $result;    
		//}catch(PDOException $e){
		//	$this->getPDOError();    
		//}
    }    
        
	//获取第一行第一列数据
    public function queryColumn($sql,$binds=array())    
    {
		try{
			$stmt = $this->dbh->prepare($sql);    
			$stmt->execute($binds);
			$result = $stmt->fetchColumn(); 
			return $result;    
		}catch(PDOException $e){
			$this->getPDOError();    
		}
    }    

	//获取所有数据，支持分页，分页参数：page,rows
    public function queryAll($sql,$binds=array(),$pagination=array())    
    {    
		if ($this->debug)
			echo $sql;    
		if(!empty($pagination['page']))
			$sql.=' limit '.(($pagination['page']-1)*$pagination['rows']).','.$pagination['rows'];
		try{
			$stmt = $this->dbh->prepare($sql);    
			$stmt->execute($binds);
			$result = $stmt->fetchAll(); 
			return $result;    
		}catch(PDOException $e){
			$this->getPDOError();    
		}
    }    

    //修改数据    
    public function update($table,$data,$where,$binds=array())  
    {    
		$sql = "UPDATE `$table` SET ";    
		foreach($data as $k=>$v)
		{
			$sql .= '`'.$k.'`=:'.$k.',';//'.mysql_escape_string($v).'",';    
			$binds[':'.$k]=$v;
		}
		$sql = rtrim($sql,',');
		if($where)
			$where = ' WHERE '.$where;
		$sql = rtrim($sql,',').$where;
		try{
			$stmt=$this->dbh->prepare($sql);
			$rows=$stmt->execute($binds);
			return $rows;	
		}catch(PDOException $e){
			$this->getPDOError();    
		}
    }    
   
    //字段递增    
    public function increase($table,$field,$where,$binds=array())    
    {    
		try{
			$sql = "UPDATE `$table` SET $field = $field + 1 where $where";    
			$stmt=$this->dbh->prepare($sql);
			$rows = $stmt->execute($binds);    
			return $rows;    
		}catch(PDOException $e){
			$this->getPDOError();    
		}
    }    
        
    //删除记录    
    public function delete($table,$where='',$binds=array())    
    {    
		$sql = 'UPDATE '.$table.' SET delete_flag=1';
		if($where)
			$sql .= ' WHERE '.$where;
		try{
			$stmt=$this->dbh->prepare($sql);
			$rows=$stmt->execute($binds);    
			return $rows;    
		}catch(PDOException $e){
			$this->getPDOError();    
		}
    }    
        
    /**   
     * 执行无返回值的SQL查询   
     *   
     */   
    public function execute($sql,$binds=array())    
    {    
		try{
			$st=$this->dbh->prepare($sql);
			$st->execute($binds);    
		}catch(PDOException $e){
			$this->getPDOError();    
		}
    }    
        
    /**   
     * 捕获PDO错误信息   
     */   
    private function getPDOError()    
    {    
        if ($this->dbh->errorCode() != '00000')    
        {    
            $error = $this->dbh->errorInfo();    
            exit($error[2]);    
        }    
    }    
}
?>
